<template>
  <div class="card fullTextManage">
    <splitpanes :dbl-click-splitter="false" style="display: flex; height: 100%; background-color: #ffffff">
      <pane size="15">
        <div class="leftTree">
          <el-tree-select
            style="width: 100%; margin: 8px 0 5px"
            check-strictly
            v-model="Fonds_ID"
            placeholder="请选择全宗"
            @change="onChange"
            node-key="Fonds_ID"
            :props="{ label: 'Fonds_Name', children: 'children' }"
            :data="FondsData"
            :render-after-expand="false"
          />
          <el-select
            style="width: 100%"
            check-strictly
            v-model="FM_ID"
            placeholder="请选择门类"
            @change="onChangeFM"
            :render-after-expand="false"
          >
            <el-option v-for="item in FMData" :key="item.FM_ID" :label="item.FM_OCName" :value="item.FM_ID" />
          </el-select>
          <!-- 搜索栏 -->
          <el-input v-model="searchVal" placeholder="请输入想要搜索的内容" enter-button @change="onSearch" />
          <ztree
            :setting="treeSetting.setting"
            :nodes="treeSetting.treeData"
            @onClick="onClick"
            @onCreated="handleCreated"
          ></ztree>
          <el-button style="padding: 20px 0" @click="noClassManage" :class="{ active: btnStatus }">无分类管理</el-button>
        </div>
      </pane>
      <pane size="85">
        <Stable
          ref="vxeTable"
          :columns="tableSetting.columns"
          :data="tableSetting.data"
          :tablePage="tableSetting.tablePage"
          :pageSizes="[20, 100, 1000, 5000, { label: '全量数据', value: -1 }]"
          :toolbarConfigVisible="true"
          @rowClick="rowClick"
          @rowdblClick="rowdblClick"
          @selectionChange="selectChange"
        >
          <template #toolbarButtons>
            <el-space style="width: 100%">
              <el-tooltip
                class="box-item"
                effect="dark"
                :content="item.title"
                placement="top"
                v-for="item in buttonList"
                :key="item"
              >
                <el-button :icon="item.icon === 'QrcodeOutlined' ? QrcodeOutlined : item.icon" @click="onClickBtn(item.title)">
                  {{ item.title }}
                </el-button>
              </el-tooltip>
            </el-space>
          </template>
        </Stable>
      </pane>
    </splitpanes>
    <!-- SingalrModal弹框 -->
    <SingalrModal
      v-model:visible="singalrModal.visible"
      :discontinueFont="singalrModal.discontinueFont"
      @cease="cease"
      @cancel="cancel"
      width="50vw"
    >
      <div style="margin-bottom: 20px; text-align: center">
        <el-text type="primary">"{{ singalrModal.text }}"</el-text>
      </div>
      <el-progress :text-inside="true" :stroke-width="20" :percentage="singalrModal.percent" status="success" />
    </SingalrModal>
    <!-- 全文预览 -->
    <preview
      v-if="fulltextConfig.visible"
      :visible="fulltextConfig.visible"
      :type="fulltextConfig.type"
      :fileList="fulltextConfig.fileList"
      :download="fulltextConfig.download"
      :print="fulltextConfig.print"
      @updataVisible="updataVisible"
    ></preview>
  </div>
</template>
<script setup lang="tsx">
import { ref, reactive, onMounted, nextTick } from "vue";
import Ztree from "@/components/ztree/Ztree.vue";
import { QrcodeOutlined } from "@ant-design/icons-vue";
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import { fileSizeFormat } from "@/utils/formatter";
import { EyeOutlined, EyeTwoTone } from "@ant-design/icons-vue";
import { getCatalog, getTreeData } from "@/views/system/catalogManage/events";
import { transTree } from "@/utils/util";
import { previewFulltext } from "@/components/Preview/ts/index";
import Preview from "@/components/Preview/Preview.vue";
import useCurrentInstance from "@/utils/useCurrentInstance";

const { proxy } = useCurrentInstance();
// 全宗数据
const FondsData = ref<any[]>([]);
// 全宗绑定字段
const Fonds_ID = ref("");
// 门类数据
const FMData = ref<any[]>([]);
// 门类绑定字段
const FM_ID = ref("");
// 搜索条件
const searchVal = ref("");
// 表格配置
const tableSetting = reactive({
  columns: [
    { type: "checkbox", width: 55 },
    { title: "序号", field: "AI_Index", width: 80, sortable: true },
    { title: "文件名", field: "AI_Name", sortable: true },
    { title: "文件类型", field: "AI_Source_Extension", width: 150, sortable: true },
    { title: "文件大小", field: "AI_Source_Size", width: 100, sortable: true, formatter: fileSizeFormat },
    { title: "上传时间", field: "AI_UploadDateTime", width: 150, sortable: true },
    { title: "创建时间", field: "AI_FileDateTime", width: 150, sortable: true },
    {
      title: "OCR状态",
      field: "AI_IsOCR",
      slots: {
        default: ({ row }: any) => {
          return [<div>{row.AI_IsOCR ? <EyeTwoTone /> : <EyeOutlined />}</div>];
        }
      }
    }
  ],
  data: [] as any[],
  tablePage: {
    showPage: true,
    pageIndex: 1,
    pageSize: 20,
    total: 0
  },
  selectData: [] as any[]
});
// 表格单击对象
const rowClickObj = ref({});
// 全宗tree配置
const treeSetting = reactive({
  setting: {
    // ztree配置
    data: {
      simpleData: {
        enable: true,
        idKey: "Catalog_ID",
        pIdKey: "Catalog_Father"
      },
      key: {
        name: "Catalog_Name"
      }
    },
    view: {
      showIcon: false
    }
  },
  treeData: [] as any[],
  treeNode: {} as any
});
// 按钮状态
const buttonList = ref([
  { title: "OCR", icon: "View" },
  { title: "MD转换", icon: "Ticket" },
  { title: "双层PDF转换", icon: "Connection" },
  { title: "打包下载", icon: "Download" },
  { title: "打开全文浏览", icon: "Document" },
  { title: "全文检索", icon: "Search" }
]);
// singalr弹框配置
const singalrModal = reactive({
  visible: false, //弹框状态
  discontinueFont: "中止", // 弹框按钮文字
  discontinueStatus: false, // 弹框按钮状态
  networkStatus: true, // 单个网络状态
  AllNetworkStatus: true, // 所有的网络状态
  circulatingIndex: 0, // 循环索引
  percent: 0, // 进度条进度
  text: "" // singal文字
});
// 获取表格实例
const vxeTable = ref();
// 无分类按钮状态
const btnStatus = ref(false);
// 初始化树对象
const ztreeObj = ref();
// 全文预览配置参数
const fulltextConfig = reactive({
  // 预览全文配置参数
  visible: false,
  fileList: [] as any[],
  type: "",
  download: false,
  print: false
});
// 搜索事件
const onSearch = () => {
  if (searchVal.value) {
    const nodes = ztreeObj.value.getNodesByParamFuzzy("Catalog_Name", searchVal.value, null);
    treeSetting.treeData = nodes;
  } else {
    onChangeFM(FM_ID.value);
  }
};
// 获取全宗数据
const getFonds = () => {
  proxy.$vueAxios.get("MasterBaseFonds/GetFondsTree").then((res: any) => {
    FondsData.value = transTree(res.List, "Fonds_ID", "Fonds_Father");
    Fonds_ID.value = res.List[0].Fonds_ID;
    onChange(Fonds_ID.value);
  });
};
// 切换全宗
const onChange = (value: string) => {
  getCatalog(value).then((res: any) => {
    FMData.value = res;
    treeSetting.treeNode = {};
  });
};
// 切换门类
const onChangeFM = (value: string) => {
  const param = {
    order: "Catalog_Order asc",
    dtoList: [{ fieldName: "FM_ID", fieldValue: value, conditionalType: 0 }]
  };
  proxy.$vueAxios.post("Master_Base_Catalog/GetConditional", param).then((res: any) => {
    const result: any[] = [];
    res.List.filter((v: any) => v.Is_UnCatalog !== true && v.Catalog_Code !== "Recycle").forEach((item: any) => {
      result.push({ ...item, Catalog_Name: `${item.Catalog_Code} ${item.Catalog_Name}`, open: item.Catalog_Enable_Expand });
    });
    treeSetting.treeData = result;
  });
};
// 初始化树
const handleCreated = (obj: any) => {
  ztreeObj.value = obj;
};
// 树节点点击事件
const onClick = (treeNode: any) => {
  treeSetting.treeNode = treeNode;
  btnStatus.value = false;
  proxy.$vueAxios
    .post("Master_Base_AllInfos/GetConditional", {
      order: "AI_Index asc",
      dtoList: [{ fieldName: "Catalog_ID", fieldValue: treeNode.Catalog_ID }]
    })
    .then((res: any) => {
      console.log("测试一下", res.List);
      tableSetting.data = res.List;
    });
};
// 点击无分类管理
const noClassManage = () => {
  btnStatus.value = true;
  ztreeObj.value.cancelSelectedNode();
  proxy.$vueAxios
    .post("Master_Base_AllInfos/GetConditional", {
      order: "AI_Index asc",
      dtoList: [{ fieldName: "Catalog_ID", fieldValue: null }]
    })
    .then((res: any) => {
      console.log("测试一下", res.List);
      tableSetting.data = res.List;
    });
};
// 表格单击事件
const rowClick = ({ row }: any) => {
  // 改变按钮状态
  vxeTable.value.setCheckboxRow([row], true);
  selectChange([row]);
  rowClickObj.value = row;
};
// 双击打开全文
const rowdblClick = ({ row }: any) => {
  previewFulltext(
    {
      id: row.AI_ID,
      fulltextRow: row,
      fulltextTableData: tableSetting.data,
      config: fulltextConfig,
      IsAllow: true
    },
    proxy
  );
};
// 更新预览窗口状态
const updataVisible = (value: boolean) => {
  fulltextConfig.visible = value;
};
// 按钮点击事件
const onClickBtn = (type: string) => {
  console.log(type);

  switch (type) {
    case "挂接全文":
      // upload();
      break;
    case "下载全文":
      // download();
      break;
    case "删除全文":
      // del();
      break;
    case "OCR":
      OCR();
      break;
    case "权限管理":
      // AuthManage();
      break;
    default:
      break;
  }
};
// 多选
const selectChange = (val: any) => {
  tableSetting.selectData = val;
};
// singalr
const signalrEvent = () => {
  proxy.signalr.off("SendExecuteContentPage");
  proxy.signalr.on("SendExecuteContentPage", (res: any) => {
    singalrModal.text = res;
    if (res.trim().startsWith("start")) {
      // 传输开始
      singalrModal.text = `正在解析第${singalrModal.circulatingIndex + 1}条...`;
    }
    if (res.trim().startsWith("stop")) {
      // 传输结束
      singalrModal.text = `第${singalrModal.circulatingIndex + 1}条已解析完成...`;
      if (singalrModal.circulatingIndex + 1 === tableSetting.selectData.length) {
        singalrModal.circulatingIndex = 0;
        singalrModal.percent = 0;
        singalrModal.visible = false;
        singalrModal.discontinueStatus = false;
        singalrModal.networkStatus = true;
        singalrModal.discontinueFont = "中止";
        singalrModal.AllNetworkStatus = false;
      }
    }
  });
};
// 全文ocr
const OCR = async () => {
  console.log(123);

  singalrModal.visible = true;
  if (!singalrModal.AllNetworkStatus) {
    singalrModal.AllNetworkStatus = true;
    singalrModal.circulatingIndex = 0;
    singalrModal.percent = 0;
  }
  for (let i = singalrModal.circulatingIndex; i < tableSetting.selectData.length; i++) {
    singalrModal.circulatingIndex = i;
    const item = tableSetting.selectData[i];
    if (singalrModal.networkStatus && singalrModal.AllNetworkStatus) {
      await proxy.$vueAxios
        .post(
          "MasterBaseSearchOCR/ExecuteContentPage",
          { idList: [item.AI_ID], clientUser: proxy.signalr.connectionId },
          { noLoading: true }
        )
        .then((res: any) => {
          if (res.Mark) {
            tableSetting.selectData.filter((v: any) => v.AI_ID === item.AI_ID)[0].AI_IsOCR = true;
          } else {
            proxy.$message.error(res.Msg);
          }
        });
      singalrModal.percent = Math.round(((singalrModal.circulatingIndex + 1) / tableSetting.selectData.length) * 100);
    } else {
      return;
    }
  }
};
// 中止请求
const cease = () => {
  singalrModal.discontinueStatus = !singalrModal.discontinueStatus;
  singalrModal.networkStatus = !singalrModal.networkStatus;
  if (singalrModal.discontinueStatus) {
    singalrModal.discontinueFont = "恢复";
  } else {
    singalrModal.discontinueFont = "中止";
  }
  OCR();
};
// 取消请求
const cancel = () => {
  singalrModal.circulatingIndex = 0;
  singalrModal.percent = 0;
  singalrModal.visible = false;
  singalrModal.discontinueStatus = false;
  singalrModal.networkStatus = true;
  singalrModal.discontinueFont = "中止";
  singalrModal.AllNetworkStatus = false;
};

onMounted(() => {
  getFonds();
  signalrEvent();
});
</script>
<style lang="scss" scoped>
.fullTextManage {
  height: 100%;
  .leftTree {
    display: flex;
    flex-direction: column;
    height: 100%;
  }
  .active {
    color: var(--el-button-active-text-color);
    background-color: var(--el-button-active-bg-color);
    border-color: var(--el-button-active-border-color);
  }
}
</style>
